package com.example.lotterysystem.controller;

import com.example.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.example.lotterysystem.common.exception.ControllerException;
import com.example.lotterysystem.common.pojo.CommonResult;
import com.example.lotterysystem.common.utils.JWTUtil;
import com.example.lotterysystem.common.utils.JacksonUtil;
import com.example.lotterysystem.controller.param.MessageLoginParam;
import com.example.lotterysystem.controller.param.UserPasswordLoginParam;
import com.example.lotterysystem.controller.param.UserRegisterParam;
import com.example.lotterysystem.controller.result.BaseUserInfoResult;
import com.example.lotterysystem.controller.result.UserLoginResult;
import com.example.lotterysystem.controller.result.UserRegisterResult;
import com.example.lotterysystem.service.IUserService;
import com.example.lotterysystem.service.IVerificationCodeService;
import com.example.lotterysystem.service.dto.UserDTO;
import com.example.lotterysystem.service.dto.UserLoginDTO;
import com.example.lotterysystem.service.dto.UserRegisterDTO;
import com.example.lotterysystem.service.enums.UserIdentityEnum;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2025/1/26
 */
@Slf4j
@RestController
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IVerificationCodeService verificationCodeService;

    /**
     * 注册
     *
     * @param param
     * @return
     */
    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(
            HttpServletRequest request,
            @Validated @RequestBody UserRegisterParam param) {
        // 日志打印
        log.info("userRegister UserRegisterParam:{}", JacksonUtil.writeValueAsString(param));
        // 调用Service层服务进行访问
        // 初始化 createId 为 null
        Integer createId = null;

        // 根据身份判断是否需要设置 createId
        if (UserIdentityEnum.NORMAL.name().equalsIgnoreCase(param.getIdentity())) {
            String userToken = request.getHeader("user_token");
            if (userToken != null) { // 确保 userToken 不为 null
                createId = JWTUtil.getUserIdFromToken(userToken);
            }
        }

        // 调用 Service 层服务进行注册
        UserRegisterDTO userRegisterDTO = userService.register(createId, param);

        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));
    }

    /**
     * 发送验证码
     *
     * @param email
     * @return
     */
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(String email) {
        log.info("目标发送邮箱：{}", email);
        verificationCodeService.sendVerificationCode(email);
        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 密码登录
     *
     * @param param
     * @return
     */
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userPasswordLogin(
            @RequestBody @Validated UserPasswordLoginParam param) {
        log.info("userPasswordLogin 接收到参数：{}",
                JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        if (userLoginDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }
        UserLoginResult userLoginResult = new UserLoginResult();
        userLoginResult.setToken(userLoginDTO.getToken());
        userLoginResult.setIdentity(userLoginDTO.getIdentity().name());
        return userLoginResult;
    }

    /**
     * 验证码登录
     *
     * @param param
     * @return
     */
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> messageLogin(
            @RequestBody @Validated MessageLoginParam param) {
        log.info("userPasswordLogin 接收到参数：{}",
                JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }


    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO registerDTO) {
        if (registerDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        UserRegisterResult result = new UserRegisterResult();
        result.setUserId(registerDTO.getUserId());
        return result;
    }

    @RequestMapping("/base-user/find-list")
    public CommonResult<List<BaseUserInfoResult>> selectBaseUserInfo(HttpServletRequest request,
                                                                     String identity) {
        log.info("selectBaseUserInfo 接收到参数：{}", identity);
        String userToken = request.getHeader("user_token");
        Integer createUserId = JWTUtil.getUserIdFromToken(userToken);

        List<UserDTO> userDTOLists = userService.selectUserInfoByIdentity(createUserId,
                UserIdentityEnum.forName(identity));
        return CommonResult.success(convertToBaseUserList(userDTOLists));
    }

    private List<BaseUserInfoResult> convertToBaseUserList(List<UserDTO> userDTOLists) {
        if (CollectionUtils.isEmpty(userDTOLists)) {
            return Arrays.asList();
        }
        return userDTOLists.stream().
                map(userDTO -> {
                    BaseUserInfoResult userInfoResult = new BaseUserInfoResult();
                    userInfoResult.setUserId(userDTO.getUserId());
                    userInfoResult.setUserName(userDTO.getUserName());
                    userInfoResult.setIdentity(userDTO.getIdentity().name());
                    return userInfoResult;
                }).collect(Collectors.toList());
    }
}
